$(function() {

    // 加载formSelects
    layui.config({
        base: '/Public/layui-formSelects/dist/'
    }).extend({
        formSelects: 'formSelects-v4'
    });

    layui.use(['layer', 'form', 'formSelects'], function () {
        var layer = layui.layer,
            form = layui.form(),
            formSelects = layui.formSelects;


        // 自定义验证规则
        form.verify({
            // 金额验证：整数兼保留两位小数
            account: function (value, item) {
                if (value && !/^[a-zA-Z]+$/.test(value)) {
                    return '账号格式错误';
                }
            },
            mail: function (value, item) {
                if (value && !/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(value)) {
                    return '邮箱格式错误';
                }
            },
            idcard: function (value, item) {
                if (value && !/^\d{17}(\d|X|x)$/.test(value)) {
                    return '身份证格式错误';
                }
            },
            age: function (value, item) {
                if (value && !/^\d{2}$/.test(value)) {
                    return '年龄错误';
                }
            },
            mobile: function (value, item) {
                if (value && !/^1[34578]\d{9}$/.test(value)) {
                    return '手机格式错误';
                }
            }
        });

        // 监听是否产线员工
        form.on('select(type)', function (data) {
            // 如果是产线员工不需要录入账号和电子邮箱
            if (data.value === '产线员工') {
                $('.layui-form input[name=account]').attr('disabled', true);
                $('.layui-form input[name=email]').attr('disabled', true);
            } else {
                $('.layui-form input[name=account]').attr('disabled', false);
                $('.layui-form input[name=email]').attr('disabled', false);
            }
            form.render();
        });

        // 监听状态改变
        form.on('select(state)', function (data) {
            // 如果选择离职则开启离职控件的选择和录入
            if (data.value == 3) {
                $('.layui-form select[name=leave_type]').attr('disabled', false);
                $('.layui-form input[name=leave_date]').attr('disabled', false);
            } else {
                $('.layui-form select[name=leave_type]').attr('disabled', true);
                $('.layui-form input[name=leave_date]').attr('disabled', true);
            }
            form.render();
        });

        $('#idCard').on('input propertychange', function (e) {
            // 如果值符合身份证格式
            if (/^\d{17}(\d|X|x)$/.test(e.target.value)) {
                var curYear = new Date().getFullYear();
                var idCard = e.target.value;
                var birthdayArr = [
                    parseInt(idCard.slice(6, 10)),  // 生日年份
                    parseInt(idCard.slice(10, 12)), // 生日月份
                    parseInt(idCard.slice(12, 14))  // 生日号数
                ];
                var age = (curYear - birthdayArr[0]) + 1;
                var birhday = birthdayArr.join('-');
                var sexNo = parseInt(idCard.slice(16, 17));
                var sex = sexNo % 2 ? '男' : '女';
                $('.layui-form input[name=age]').val(age);
                $('.layui-form input[name=birthday]').val(birhday);
                $('.layui-form input[name=sex][value=' + sex + ']').prop('checked', true);
                $('.layui-form input[name=sex][value!=' + sex + ']').prop('checked', false);
                form.render();
            }
        });

        $('.is-date').datetimepicker({
            minView: 'month',
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            // weekStart: 1,
            todayBtn: true,
            autoclose: true,
            todayHighlight: true,
        }).on('changeDate', function (ev) {
            // 如果是入职日期则计算工龄
            if (ev.target.name == 'entry_date') {
                var str = '';
                var obj = getDiffYmdBetweenDate(ev.target.value, new Date().toLocaleDateString().replace(/\//g, '-'));
                if (obj.y) {
                    str += obj.y + '年';
                }
                if (obj.m) {
                    str += obj.m + '个月';
                }
                if (obj.d) {
                    str += obj.d + '天';
                }
                $('.layui-form input[name=work_age]').val(str);
            }
        });

        // 执行渲染, 把原始select美化
        formSelects.render('permissions');
        formSelects.render('post');

        form.on('submit(create)', function (data) {
            data.field.permissions = formSelects.value('permissions', 'valStr');
            data.field.post = formSelects.value('post', 'valStr');
            var loading = layer.load(2, {
                shade: [0.5, '#fff']
            });
            store(data.field).then(function (res) {
                location.href = '/manage/show?id=' + res.id;
            });
        });

        function store(data)
        {
            return new Promise(function (resolve, reject) {
                $.post('/manage/store', data, function (response) {
                    if (response.errno) {
                        layer.closeAll();
                        layer.alert(response.message, {icon: 2});
                    } else {
                        resolve(response.data);
                    }
                });
            });
        }
    });

});
